<?php

namespace app\common\library;

use think\Log;
use think\Env;
use think\Db;
use think\Exception;
use app\admin\model\pt\Depart as DepartModel;
use app\admin\model\pt\Job as JobModel;
use app\admin\model\pt\PlanMonth as MonthModel;
use app\admin\model\pt\PlanRange as RangeModel;
use app\admin\model\pt\JobPlan as PlanModel;


class Plan
{
    protected $_monthModel = null; 
    protected $_rangeModel = null;
    protected $_jobPlanModel = null;

    public function __construct()
    {
        $this->_monthModel = new MonthModel();
        $this->_rangeModel = new RangeModel();
        $this->_jobPlanModel = new PlanModel();
    }

    public function handleMonthPlan($planData, $yearId, $departId)
    {
        $departInfo = DepartModel::where('id', $departId)->find();
        if (!$departInfo) {
            Log::write('部门信息未找到, id =>' . $departId);
            throw new Exception('部门信息未找到');
        }
        if ($departInfo->status != 'normal') {
            Log::write('部门信息已隐藏, id =>' . $departId . ', status =>' . $departInfo->status);
            throw new Exception('部门信息已隐藏');
        }

        foreach ($planData as $pd) {
            $pd['fee_total'] = $pd['fee_total'] ?? 0;
            $pd['parttime_total'] = $pd['parttime_total'] ?? 0;
            $pd['intern_total'] = $pd['intern_total'] ?? 0;
            $pd['pt_depart_id'] = $departId;
            $pd['year_id'] = $yearId;
            // 查找有无对应月份 
            $planInfo = $this->_monthModel->where('pt_depart_id', $departId)
              ->where('year_id', $yearId)
              ->where('month_id', $pd['month_id'])
              ->find();
            if ($planInfo) {
                $pd['id'] = $planInfo->id;
            } else {
                $planInfo = new MonthModel();
            }
            $planInfo->save($pd);
        }
    }

    public function handleRangePlan($startDate, $endDate, $departId, $planTotal, $id = 0)
    {
        // 检查开始和结束是否在同一个月 
        if (date('m', strtotime($startDate)) != date('m', strtotime($endDate))) {
            Log::write('开始日期和结束日期跨月了 =>' . $startDate . " - " . $endDate);
            throw new Exception('开始日期和结束日期跨月了');
        }
        $startDateId = date('Ymd', strtotime($startDate));
        $endDateId = date('Ymd', strtotime($endDate));
        if ($endDateId < $startDateId) {
            throw new Exception('开始日期大于结束日期了');
        }
        
        // 开始日期或结束日期不能被包含在其他时间段内
        $checkRes = Db::name('pt_plan_range')
          ->where("'".$startDateId."' >=start_date_id and '".$startDateId."'<=end_date_id")
          ->where('pt_depart_id', $departId);
        if (!empty($id)) {
            $checkRes = $checkRes->where('id', '<>', $id);
        }

        $checkRes = $checkRes->find();
        if ($checkRes) {
            throw new Exception('开始日期包含在其他区间计划内');
        }
        $checkRes = Db::name('pt_plan_range')
          ->where("'".$endDateId."' >=start_date_id and '".$endDateId."'<=end_date_id")
          ->where('pt_depart_id', $departId);
        if (!empty($id)) {
            $checkRes = $checkRes->where('id', '<>', $id);
        }
        $checkRes = $checkRes->find();
        if ($checkRes) {
            throw new Exception('结束日期包含在其他区间计划内');
        }

        $params = [];
        $params['pt_depart_id'] = $departId;
        $params['start_date_id'] = $startDateId;
        $params['end_date_id'] = $endDateId;
        $params['plan_total'] = $planTotal;
        if (!empty($id)) {
            $rangeInfo = $this->_rangeModel->get($id);
        } else {
            $rangeInfo = new RangeModel();
        }
        $rangeInfo->save($params);

    }

    public function checkJobPlan($jobId, $dateId, $addedTotal = 1, $throw = true)
    {
        $jobInfo = PlanModel::where('date_id', $dateId)->where('pt_job_id', $jobId)->find();
        $err = '';
        if (!$jobInfo) {
            $err = date('Y-m-d', strtotime($dateId)) . '日未安排岗位日计划, 安排失败';
        }
        if (empty($err)) {
            // 判断是否超过人数
            $consumedTotal = $jobInfo->consume_total + $addedTotal;
            Log::write('check job plan consume total => ' . $jobInfo->consume_total);
            Log::write('check job plan plan total => ' . $jobInfo->plan_total);
            Log::write('check job plan consumedTotal => ' . $consumedTotal);
            Log::write('check job plan addedTotal => ' . $addedTotal);
            if ($consumedTotal > $jobInfo->plan_total) {
                $err = date('Y-m-d', strtotime($dateId)) . '安排人次总数超过岗位日计划人次, 安排失败';
            }
        }

        if ($throw && !empty($err)) {
            throw new Exception($err);
        }

        return $err;
    }

    public function handleJobPlan($startDate, $endDate, $jobId, $planTotal)
    {
        $startDateId = date('Ymd', strtotime($startDate));
        $endDateId = date('Ymd', strtotime($endDate));
        if ($endDateId < $startDateId) {
            throw new Exception('开始日期大于结束日期了');
        }
        $jobInfo = JobModel::get($jobId);
        if (!$jobInfo) {
            throw new Exception('岗位信息未找到');
        }
        if ($jobInfo->status != 'normal') {
            throw new Exception('岗位信息已隐藏');
        }

        $departId = $jobInfo->pt_depart_id;

        for ($date = $startDateId; $date <= $endDateId; $date++)
        {
            $this->saveJobPlan($jobId, $departId, $date, $planTotal);
        }
    }

    public function consumeJobPlan($jobId, $departId, $dateId, $consumeTotal = 0)
    {
        $checkDate = date('Ymd', strtotime($dateId));
        if ($checkDate != $dateId) {
            return;
        }
        // 如果没有传
        if ($consumeTotal) {
        }
        if (empty($departId)) {
            $jobInfo = JobModel::get($jobId);
            $departId = $jobInfo->pt_depart_id;
        }
        $planInfo = $this->_jobPlanModel->where('pt_depart_id', $departId)
                         ->where('pt_job_id', $jobId)
                         ->where('date_id', $checkDate)
                         ->find();
        $planInfo->consume_total = $consumeTotal;
        $planInfo->save();
    }

    public function calDepartPlan($rangeStartDate, $rangeEndDate, $departId, $id = 0)
    {
        $rangeStartId = date('Ymd', strtotime($rangeStartDate));
        $rangeEndId = date('Ymd', strtotime($rangeEndDate));
        if (!$id) {
            $range = RangeModel::where('start_date_id', $rangeStartId)->where('end_date_id', $rangeEndId)
                                                                     ->where('pt_depart_id', $departId)
                                                                     ->find();
        } else {
            $range = RangeModel::get($id);
        }
        // 查询这个范围的
        $consumeTotalFee = Db::name('pt_person_salary')->where('pt_depart_id', $departId)
                                                ->where('salary_total', '>', 0)
                                                ->where('date_id', '>=', $rangeStartId)
                                                ->where('date_id', '<=', $rangeEndId)
                                                ->sum('salary_total');
        // 计算已消耗人次
        $consumeTotalPersons = Db::name('pt_duty_list')->where('pt_depart_id', $departId)
                                                ->where('date_id', '>=', $rangeStartId)
                                                ->where('date_id', '<=', $rangeEndId)
                                                ->count('id');
        $range->consume_total = $consumeTotalPersons;
        $range->consume_fee = $consumeTotalFee;
        $range->save();
        // 部门设置的本月费用
        $curMonth = date('Ym', strtotime($rangeStartId));
        $yearId = date('Y', strtotime($rangeStartId));
        $monthId = date('n', strtotime($rangeStartId));
        $monthData = Db::name('pt_plan_month')->where('year_id', $yearId)
                                              ->where('month_id', $monthId)
                                              ->where('pt_depart_id', $departId)
                                              ->find();

        $calFeeTotal = $monthData['fee_total']; 
        $monthFeeTotal = $monthData['fee_total'];
        $rangeModels = RangeModel::where('pt_depart_id', $departId)->where('start_date_id', 'like', $curMonth . '%')->order('start_date_id', 'asc')->select();
        foreach ($rangeModels as $r) {
            $calFeeTotal = $calFeeTotal - $r->consume_fee;
            $r->remain_fee = $calFeeTotal; 
            $r->remain_percent = round(($calFeeTotal / $monthFeeTotal * 100), 2);
            $r->save();
        }
    
    }

    private function saveJobPlan($jobId, $departId, $dateId, $planTotal)
    {
        $checkDate = date('Ymd', strtotime($dateId));
        if ($checkDate != $dateId) {
            return;
        }
        $params = []; 
        $params['pt_depart_id'] = $departId;
        $params['pt_job_id'] = $jobId;
        $params['date_id'] = $dateId;
        $params['plan_total'] = $planTotal;
        // 查找有无对应日期的工作安排
        $planInfo = $this->_jobPlanModel->where('pt_job_id', $jobId)->where('date_id', $dateId)->find();
        if (!$planInfo) {
            $planInfo= new PlanModel();
        } else {
            $params['id'] = $planInfo->id;
        }
        $planInfo->save($params);
    }
}
